<script setup>
import {reactive, ref, watch} from 'vue'
import {FolderOpened, Folder, Search} from "@element-plus/icons-vue";
import requestUtil from "@/utils/request";
import {ElMessage} from "element-plus";

const tableData = ref([])

const treeProps = reactive({
  checkStrictly: false,
})

const treeData = ref([])
const tableRef = ref(null)
const title = ref('')

const total = ref(0)

const queryForm = ref({
  query: '',
  pageNum: 1,
  pageSize: 8,
  group_id: 0
})

const hostTuple = ref([])
const multipleTableRef = ref(null)

const multipleTable = ref(null)

const selectedId = ref(null)
const srcSelectRow = ref(null)

// dialogStatus 1：目标主机、2：源主机、3：批量执行
const props = defineProps({
  dialogStatus: {
    type: Number,
    default: 0,
    required: true
  },
  dialogTitle: {
    type: String,
    default: '',
    required: true
  },
  dialogVisible: {
    type: Boolean,
    default: false,
    required: true
  },
})


const initTableData = async (val) => {
  try {
    if (val) {
      if (val.id) {
        queryForm.value.group_id = val.id
      }
    }
    const res = await requestUtil.post('host/list', queryForm.value)
    const data = res.data
    if (data.code === 200) {
      tableData.value = data.msg
      total.value = data.total
    } else {
      ElMessage.error(data.msg)
    }
  } catch (error) {
    console.error('Error fetching table data:', error)
    ElMessage.error('请求失败，请稍后再试')
  }

}

const handlePageChange = (pageNum) => {
  queryForm.value.pageNum = pageNum
  initTableData()
}

const handleSizeChange = (pageSize) => {
  queryForm.value.pageNum = 1
  queryForm.value.pageSize = pageSize
  initTableData()
}

const handleCurrentChange = async (val) => {
  await initTableData(val)
}

const initTreeData = async () => {
  try {
    const res = await requestUtil.get('host/group/list')
    const data = res.data
    if (data.code === 200) {
      treeData.value = data.msg
    } else {
      ElMessage.error(data.msg)
    }
  } catch (error) {
    console.error('Error fetching table data:', error)
    ElMessage.error('请求失败，请稍后再试')
  }
}
initTreeData()


const emits = defineEmits(['update:modelValue', 'sendTuple'])


const handleClose = () => {
  emits('update:modelValue', false);
  if (multipleTable.value) {
    multipleTable.value.clearSelection();
  }
  tableRef.value.setCurrentRow(null);
  queryForm.value.pageSize = 8;
}

// 点击事件触发emit，传递元组给父组件
const sendTuple = (tuple) => {
  emits('sendTuple', tuple);
};
const handleConfirm = async () => {
  if (props.dialogStatus === 2) {
    // if (srcSelectRow.value.server_type === 2) {
    //   ElMessage.warning('不能选择windows主机，请到终端管理页面，管理windows文件')
    //   return
    // }
    sendTuple(srcSelectRow)
    handleClose()
  } else {
    let idList = []
    let serverType = 0
    for (const row of hostTuple.value) {
      idList.push(row)
    }
    if (serverType === 1) {
      return
    }
    sendTuple(idList)
    handleClose()
  }
}


const handleSelectionChange = (selection) => {
  hostTuple.value = selection.filter(row => row.id);
}

const handleRadioChange = (row) => {
  srcSelectRow.value = row
}

watch(
    () => props.dialogVisible,
    () => {
      if (props.dialogVisible === true) {
        queryForm.value.group_id = 0;
        initTableData();
        title.value = props.dialogTitle;
      }
    }
)
</script>

<template>
  <el-dialog
      ref="multipleTableRef"
      :close-on-click-modal="false"
      :model-value="dialogVisible"
      :title="title"
      style="padding: 40px;margin-top: 30px"
      width="1220px"
      @close="handleClose"
  >
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card style="height: 650px">
          <template v-slot:header>
            <span>分组列表</span>
          </template>
          <el-table
              ref="tableRef"
              :data="treeData"
              :tree-props="treeProps"
              row-key="id"
              height="550px"
              default-expand-all
              :show-header="false"
              highlight-current-row
              @current-change="handleCurrentChange"
          >
            <el-table-column class="clearfix">
              <template #default="scope">
                <el-icon>
                  <FolderOpened v-if="Array.isArray(scope.row.children) && scope.row.children.length > 0"/>
                  <Folder v-else/>
                </el-icon>
                &nbsp;<span>{{ scope.row.name }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <el-col :span="18">
        <el-card style="height: 650px">
          <template v-slot:header>
            <div class="space-between">
              <div>
                <span>服务器信息</span>
              </div>
              <div>
                <el-input clearable placeholder="IP/主机名称" v-model="queryForm.query"
                          style="max-width: 150px;margin-right: 10px" size="default"></el-input>
                <el-button size="default" :icon="Search" type="warning" @click="initTableData(queryForm.query)">搜索
                </el-button>
              </div>
            </div>
          </template>

          <el-table
              ref="multipleTable"
              :data="tableData"
              stripe
              style="width: 100%"
              row-key="id"
              height="550px"
              @selection-change="handleSelectionChange"
          >

            <el-table-column width="50" v-if="props.dialogStatus === 2">
              <template #default="scope">
                <el-radio
                    v-model="selectedId"
                    :label="scope.row.id"
                    @change="handleRadioChange(scope.row)"
                ></el-radio>
              </template>
            </el-table-column>

            <el-table-column type="selection" width="55" v-else/>
            <el-table-column prop="hostname" label="主机名称" width="240"/>
            <el-table-column width="180" label="IP地址">
              <template v-slot="scope">
                <div v-if="scope.row.public_ip_addr">
                  <span class="public">公</span>
                  <span>{{ scope.row.public_ip_addr }}</span>
                </div>
                <div v-if="scope.row.private_ip_addr">
                  <span class="private">内</span>
                  <span>{{ scope.row.private_ip_addr }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="config_info" label="配置信息" width="240"/>
            <el-table-column prop="status" label="状态" width="80">
              <template v-slot="scope">
                <span v-if="scope.row.status === 0" class="el-tag el-tag--danger">验证失败</span>
                <span v-else-if="scope.row.status === 1" class="el-tag el-tag--warning">未验证</span>
                <span v-else class="el-tag el-tag--success">已验证</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <template #footer>
      <div class="page-class">
        <el-pagination
            style="margin: 20px;"
            :hide-on-single-page="true"
            v-model:currentPage="queryForm.pageNum"
            v-model:page-size="queryForm.pageSize"
            :page-sizes="[8, 16, 24, 32]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
        />
        <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.page-class {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 20px;
}

.space-between {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 14px;
}

.public {
  background: rgb(255, 231, 186);
  border-radius: 4px;
  color: rgb(51, 51, 51);
  margin-right: 4px;
  padding: 0 8px;
}

.private {
  background: rgb(186, 231, 255);
  border-radius: 4px;
  color: rgb(51, 51, 51);
  margin-right: 4px;
  padding: 0 8px;
}

.selected-row {
  background-color: #398dff; /* 选中行的背景色 */
}
</style>
